package com.snail.starter.feign.decode;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.snail.starter.commons.result.ApiResult;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

/**
 * @author: snail framework
 * @Date: 2023/2/22 下午4:42
 * @Version: 1.0.0
 */
@Slf4j
@Component
public class BasicFeignResponseDecode implements Decoder {

    @Resource
    ObjectMapper objectMapper;

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        byte[] requestBody = response.request().body();
        String responseBody = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
        log.info("Response Feign,url:{},method:{},request body:{}, response body:{}", response.request().url(), response.request().httpMethod(), requestBody, responseBody);
        ApiResult<?> result = objectMapper.readValue(responseBody, ApiResult.class);
        if (null == result) {
            return null;
        }
        return result.getData();
    }

}